package com.ksd;

import com.ksd.common.config.PlayControlConfig;
import com.ksd.common.utils.StringUtils;
import com.ksd.common.utils.ip.IpUtils;
import com.ksd.common.utils.spring.SpringUtils;
import com.ksd.quartz.task.ByoImportTask;
import com.ksd.quartz.task.HardDiskImportTask;
import com.ksd.system.domain.SysContentSynch;
import com.ksd.system.domain.SysNetwork;
import com.ksd.system.service.ISysContentSynchService;
import com.ksd.system.service.ISysNetworkService;
import com.ksd.system.service.ISysRoleService;
import com.ksd.web.controller.system.FirstController;
import com.ksd.web.controller.system.SysNetworkController;
import com.ksd.web.controller.tool.SubnetMaskConversion;
import com.ksd.web.controller.tool.SysNetworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.scheduling.annotation.EnableAsync;

import java.io.IOException;
import java.util.Map;

/**
 * 启动程序
 * 
 * @author ruoyi
 */
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
@EnableAsync
public class PlayControlApplication
{
    private static final Logger logger = LoggerFactory.getLogger(PlayControlApplication.class);
    public static void main(String[] args)
    {
        ConfigurableApplicationContext context = SpringApplication.run(PlayControlApplication.class, args);
        printKeyLoadMessage(context);

    }


    // 新增此方法，项目启动后自动执行
    @Bean
    public CommandLineRunner runByoImportTask(ByoImportTask byoImportTask) {
        logger.info("开始进行服务器本地指定地址的内容检测导入资源");
        return args -> {
            try {
                // 执行服务器本地导入任务
                byoImportTask.getMovieAndSong();
                logger.info("项目启动时已执行服务器本地资源文件导入任务");
            } catch (IOException e) {
                logger.info("启动时执行服务器本地资源文件导入任务失败：" + e.getMessage());
                e.printStackTrace();
            }
        };
    }
//    @Bean
//    public CommandLineRunner runHardDiskImportTask(HardDiskImportTask hardDiskImportTask) {
//        logger.info("开始进行硬盘指定地址的内容检测导入资源");
//        return args -> {
//            try {
//                // 执行硬盘导入任务
//                hardDiskImportTask.getMovieAndSong();
//                logger.info("项目启动时已执行硬盘导入任务");
//            } catch (IOException e) {
//                logger.info("启动时执行硬盘导入任务失败：" + e.getMessage());
//                e.printStackTrace();
//            }
//        };
//    }


    /**
     * 获取Key加载信息
     */
    public static boolean printKeyLoadMessage(ConfigurableApplicationContext context) {


        ConfigurableEnvironment environment = context.getEnvironment();
        // 项目端口
        String port = environment.getProperty("server.port");
        // 项目路径
        String contextPath = environment.getProperty("server.servlet.context-path");
        // 项目名称
        // String projectFinalName = environment.getProperty("server.servlet.context-path");

        String homeUrl = "http://" + IpUtils.getHostIp() + ":" + port + contextPath;

        StringBuilder sb = new StringBuilder();
        sb.append("\r\n======================================================================\r\n");
        sb.append("\r\n            (♥◠‿◠)ﾉﾞ  政企后台管理系统启动成功   ლ(´ڡ`ლ)ﾞ  \r\n");
        sb.append("\r\n    欢迎使用 " + PlayControlConfig.getName() + "  - Version : " + PlayControlConfig.getVersion() + ".RELEASE\r\n");
        sb.append("\r\n======================================================================\r\n");
        logger.info("\thomeUrl:    " + homeUrl);
        logger.info("\r");

        if (!checkDataInit()){
            return false;
        }


        return true;
    }
    //校验数据库初始化数据是否存在
    public static boolean  checkDataInit() {

        ISysContentSynchService sysContentSynchService = SpringUtils.getBean(ISysContentSynchService.class);
        SysContentSynch sysContentSynch = sysContentSynchService.selectSysContentSynchById(SysContentSynch.synch_jar_id);
        sysContentSynch.setValue1(PlayControlConfig.getVersion());
        logger.info("当前部署的系统版本:"+sysContentSynch.getValue1());
        sysContentSynchService.updateSysContentSynch(sysContentSynch);

        ISysNetworkService sysNetworkService = SpringUtils.getBean(ISysNetworkService.class);
        SysNetwork sysNetworkDefault = sysNetworkService.selectSysNetworkById(SysNetwork.defaultId);
        SysNetwork sysNetworkDefault1 = sysNetworkService.selectSysNetworkById(SysNetwork.eth1_id);
        SysNetwork sysNetworkDefault2 = sysNetworkService.selectSysNetworkById(SysNetwork.eth2_id);
        if (StringUtils.isNull(sysNetworkDefault) || StringUtils.isNull(sysNetworkDefault1) || StringUtils.isNull(sysNetworkDefault2)) {
            logger.info("sys_network 表的默认策略不存在,请检查数据库.要求ID:" + SysNetwork.defaultId +","+SysNetwork.eth1_id+","+SysNetwork.eth2_id);
            return false;
        }

        //check 当前服务器的网络配置文件是否能够正常读取
        String os = System.getProperty("os.name").toLowerCase();
//        System.out.println("os:" + os);
        if (os.startsWith("win")) {
            SysNetwork sysNetwork1 = sysNetworkService.selectSysNetworkById(sysNetworkDefault.defaultId);
            String subnetMask = sysNetwork1.getSubnetMask();
            if (subnetMask.indexOf(".") == -1){
                String mask = SubnetMaskConversion.convertCidrToDottedDecimal(Integer.valueOf(subnetMask));
                sysNetwork1.setSubnetMask(mask);
            }
            return true;
        } else {
            String networkX86Path = PlayControlConfig.getNetworkX86Path();
            Map<String, String> stringStringMap = SysNetworkController.readConfig(networkX86Path);
            String ip = stringStringMap.get("ip");
            String netmask = stringStringMap.get("netmask");
            String gateway = stringStringMap.get("gateway");
            SysNetwork sysNetwork1 = sysNetworkService.selectSysNetworkById(sysNetworkDefault.defaultId);
            if (netmask.indexOf(".") == -1){
                netmask = SubnetMaskConversion.convertCidrToDottedDecimal(Integer.valueOf(netmask));
            }
            if (StringUtils.isNotEmpty(ip) && StringUtils.isNotEmpty(netmask) && StringUtils.isNotEmpty(gateway)){
                sysNetwork1.setIp(ip);
                sysNetwork1.setGateway(gateway);
                sysNetwork1.setSubnetMask(netmask);
                sysNetworkService.updateSysNetwork(sysNetwork1);
                return true;
            }else {
                logger.info("服务器网络地址配置文件读取失败,请确认文件地址:" + networkX86Path);
                return false;
            }
        }
    }
}
